#include "main_header.h"
#include "main_header.h"
int use_gets(int netfd, char *filename,file_t *file) {
  train_t train;
  int fd = open(filename, O_RDONLY);
  if (fd < 0) {
    train.type = FAILURE;
    strcpy(train.data, "文件不存在\n");
    train.length = strlen(train.data) + 1;
    send(netfd, &train.type, sizeof(train.type), 0);
    send(netfd, &train.length, sizeof(train.length), 0);
    send(netfd, train.data, train.length, 0);
    return -1;
  }
  // 发送文件名
    train.length = strlen(filename) + 1;
    memcpy(train.data, filename, train.length);
    send(netfd, &train.length, sizeof(train.length), 0);
    send(netfd, train.data, train.length, 0);


  // 发送文件大小
  struct stat file_stat;
  fstat(fd, &file_stat);
  off_t file_size = file_stat.st_size;
  train .length = sizeof(off_t);
  memcpy(train.data, &file_size, sizeof(off_t));
  send(netfd, &train.length, sizeof(train.length), 0);
  send(netfd, train.data, train.length, 0);

  // 接收已下载的size(断点续传)
  off_t offset = 0;
  recvn(netfd, &offset, sizeof(off_t));
  lseek(fd, offset, SEEK_SET);

  // 判断文件大小
  if (file_size > 100 * 1024 * 1024) {
    off_t sent_size = offset;
    while (sent_size < file_size) {
      ssize_t to_send = file_size - sent_size;
      if(to_send > 100*1024*1024)
      to_send=100*1024*1024;
      ssize_t sent = sendfile(netfd, fd, &sent_size, to_send);
      if (sent <= 0){
        break;
      }
    }
      printf("bigFile finished\n");
  } else {
    // 普通传输
    off_t sent_size = offset;
    off_t slice = file_size / 10000;
    while (1) {
      int datalen = read(fd, train.data, sizeof(train.data));
      if (datalen == 0)
            {
                // 发送空包给服务器
                send(netfd, &datalen, sizeof(int),MSG_NOSIGNAL);
                break;
            }
      send(netfd, &datalen, sizeof(datalen), 0);
      send(netfd, train.data, datalen, 0);
      sent_size += datalen;
    }
      printf("shortFile finishe\n");
  }
  close(fd);
  return 0;
}